package org.xbl.xchain.sdk.querier;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ABCIResponse {

    private Response response;

    public Boolean isSuccess() {
        if (response == null) {
            return false;
        }
        return response.getCode() != null && response.getCode() == 0;
    }

    public static ABCIResponse valueOf(Object object) {
        if (object == null || !(object instanceof Map)) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(object), ABCIResponse.class);
    }

    public <T> List<T> list(Class<T> clazz) {
        if (!isSuccess() || StringUtils.isBlank(response.getValue())) {
            return new ArrayList<>();
        }
        byte[] decode = Base64.getDecoder().decode(response.getValue());
        String data = new String(decode);
        if ("null".equals(data)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(data, clazz);
    }

    public <T> T singleResult(Class<T> clazz) {
        if (!isSuccess() || StringUtils.isBlank(response.getValue())) {
            return null;
        }
        byte[] decode = Base64.getDecoder().decode(response.getValue());
        String result = new String(decode);
        return JSON.parseObject(result, clazz);
    }

    public String stringResult() {
        if (!isSuccess() || StringUtils.isBlank(response.getValue())) {
            return null;
        }
        byte[] decode = Base64.getDecoder().decode(response.getValue());
        return new String(decode);
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Response {
        private Integer code;
        private String log;
        private String value;
    }
}
